<?php
  /**
   * This class provides Caching methods
   *
   * @author Macdonald Terrence Robinson
   * @package Core
   *
   */
  final class Cache
  {    
    private static function getCachePath()
    {
      $controller = Router::$controller;
      $function = Router::$function;
      
      return self::getCachePathBy($controller, $function);
    }
    
    private static function getCachePathBy($controller, $function)
    {
      $cacheFileName = strtolower(Config::$siteLanguage.'-'.$controller.'-'.$function.'.php');
      return Config::$cacheDir.$cacheFileName;
    }
    
    public static function clearCacheBy($controller, $function)
    {
      $cacheFilePath = self::getCachePathBy($controller, $function);
      unlink($cacheFilePath);
    }
    
    public static function clear()
    {        
      return FileSystem::emptyDir(Config::$cacheDir);
    }
    
    public static function loadCache()
    {
      if(self::isCacheValid())
        return file_get_contents( self::getCachePath() )."<!-- Loaded from cache -->\r\n";

      return '';
    }
    
    public static function saveCache( $data )
    {
      if(!self::isCacheValid());
        FileSystem::saveData( self::getCachePath(), $data, false, 0777 );
    }
    
    public static function isCacheValid()
    {
      $cachePath = self::getCachePath();
      
      if( !FileSystem::fileExists($cachePath) )
        return false;
      
      $duration = Config::$cacheDuration;
      $lastModified = filemtime( $cachePath );
      
      if((time() - $lastModified) > $duration)
        return false;
        
      $controller =  Router::$controller;
      $function = Router::$function;
      
      $disableList = Config::$disableCaching;
      
      if(in_array($controller.'/'.$function, $disableList))
        return false;
        
      return true;
    }

  }
?>
